using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public abstract class Ennemy : MovingElement 
{
	static public List<Ennemy> sSpawnedEnnemy = new List<Ennemy>();
	
	public int StartingTime;
	
	public float LoosingSeconds = 10.0f;
	public float AddingTime = 10.0f;
	public int MaxLife;
	
	protected Range mWalkableRect;
	protected int Life;
	protected Range mUntouchedRange;
	
	/// <summary>
	/// Called when the ennemy is spawned. Rect is the walkable rect of the line on wich the ennemy was spawned.
	/// </summary>
	public virtual void Spawned(Range pRange)
	{
		mUntouchedRange = pRange;
		mWalkableRect = new Range(pRange.Top - collider.bounds.extents.y, pRange.Bottom + collider.bounds.extents.y);
		
		Life = MaxLife;
		
		PostSpawnProcess();
		
		sSpawnedEnnemy.Add(this);
	}
	
	void OnDestroy()
	{
		sSpawnedEnnemy.Remove(this);
	}
	
	/// <summary>
	/// Override this to add specific behaviour after the spawn
	/// </summary>
	protected virtual void PostSpawnProcess()
	{
	}
	
	protected virtual void Die()
	{
		Destroy(GetComponent<Collider>());
		SendMessage("OnDetruit");
		
		gameObject.AddComponent<DieScript>();
		
		Destroy(this);
	}
	
	protected void OnTriggerEnter(Collider pOther)
	{
		if(pOther.tag == "Shield")
		{
			Die();
		}
		
		if(pOther.tag == "Player")
		{
			LevelGenerator.sTime -= LoosingSeconds;
			
			if(pOther.gameObject.GetComponent<NegativeBlinking>() == null)
			{
				pOther.gameObject.AddComponent<NegativeBlinking>().StartBlinking(0.2f);
			}
			
			pOther.SendMessage("OnHit");
			Die();
			//Destroy(gameObject);
			return;
		}
		
		if(pOther.tag == "Bullet")
		{
			if(!pOther.GetComponent<Bullet>().acc_playerOwned)
				return;
			
			
			Life -= player.Instance.acc_PowerCoef;

			if(Life <= 0)
			{
				LevelGenerator.sTime += AddingTime;
				Die();
			}
			else
			{
				SendMessage("OnHurt");
			}
			
			return;
		}
	}
}
